const express = require('express');
const  router = express.Router();

// 添加订单
router.post('/add' ,async (req,res)=>{
    const { Norder }  = req.Model;
    let {
        type, // 房间类型
        price, // 价格
        orderTime, //下单时间
        checkIn, // 入住时间
        checkOut, // 退房时间
        username, //客户id
        phone, //手机号
        openid, //身份证号码
        roomname //房间名
      }  = req.body;
    
     // 数据过滤的操作 

     try {
        await Norder.create({
            type, // 房间类型
            price, // 价格
            orderTime, //下单时间
            checkIn, // 入住时间
            checkOut, // 退房时间
            username, //客户id
            phone, //手机号
            openid, //身份证号码
            roomname //房间名
        })
        res.send({success:true,info:'添加成功'})
     } catch(e) {
        res.send({success:false,info:'添加失败'})
     }

        

})


router.post('/edit' ,async (req,res)=>{
  const { Norder }  = req.Model;

     // 数据过滤的操作 
    const { norderid ,...updateData} = req.body;; 

   try {
      await Norder.findByIdAndUpdate(norderid,updateData);
      res.send({success:true,info:'修改成功'})
   } catch(e) {
      res.send({success:false,info:'修改失败'})
   }

})



// 分页查询
router.post('/getAll', async (req,res)=>{
  const { Norder } = req.Model;
  let { page=1,limit=30 ,price,phone,openid,roomname,checkIn,checkOut} = req.body;
  const skip =  (page - 1 ) * limit; 

    
  let where = {  }
 if(price) where.price = price
 if(phone) where.phone = phone
 if(openid) where.openid = openid
 if(roomname) where.roomname = roomname
 if(checkIn) where.checkIn = checkIn
 if(checkOut) where.checkOut = checkOut
   try {
     let orders = await Norder.find(where, {}, { skip, limit })
     let count = await Norder.count(where)
     
     res.send({success:true,info:'查询成功',data:orders,count});
   } catch (e) {
     res.send({success:false,info:'获取失败'})
   }

})

// 查询单个房间信息

router.post('/getOne', async (req,res)=>{
  const { Norder} = req.Model;

  let { norderid } = req.body;

  if(!norderid) return res.send({success:false,info:'请传入一个正确的id'})

  try {

    let order = await Norder.findById(norderid) // 分页查询
   
    res.send({success:true,info:'查询成功',data:order});
    
  }catch(e){

    res.send({success:false,info:'获取失败'})
  }

})


router.post('/del', async (req,res)=>{
  const { Norder} = req.Model;
  let { norderid } = req.body;

  if(!norderid) return res.send({success:false,info:'请传入一个正确的id'})

  try {

    await Norder.findByIdAndRemove(norderid) 
   
    res.send({success:true,info:'删除成功'});
    
  }catch(e){

    res.send({success:false,info:'删除失败'})
  }

})


module.exports = router;